// ignore_for_file: unused_import, avoid_print

import 'dart:async';
import 'dart:io';
import 'dart:math';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tencent_calls_uikit/tencent_calls_uikit.dart';
import 'package:tencent_chat_i18n_tool/tencent_chat_i18n_tool.dart';
import 'package:tencent_cloud_chat_demo/config.dart';
import 'package:tencent_cloud_chat_demo/db/custom_sticker.dart';
import 'package:tencent_cloud_chat_demo/src/pages/forget.dart';
import 'package:tencent_cloud_chat_demo/src/pages/home_page.dart';
import 'package:tencent_cloud_chat_demo/src/pages/privacy/privacy_webview.dart';
import 'package:tencent_cloud_chat_demo/src/pages/register.dart';
import 'package:tencent_cloud_chat_demo/src/provider/theme.dart';
import 'package:tencent_cloud_chat_demo/src/routes.dart';
import 'package:tencent_cloud_chat_demo/utils/GenerateTestUserSig.dart';
import 'package:tencent_cloud_chat_demo/utils/authService.dart';
import 'package:tencent_cloud_chat_demo/utils/commonUtils.dart';
import 'package:tencent_cloud_chat_demo/utils/request.dart';
import 'package:tencent_cloud_chat_demo/utils/toast.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:tencent_cloud_chat_uikit/theme/color.dart';

class LoginPage extends StatelessWidget {
  final Function? initIMSDK;
  const LoginPage({Key? key, this.initIMSDK}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Provider.of<DefaultThemeData>(context).theme;
    return WillPopScope(
        onWillPop: () async {
          return false;
        },
        child: Scaffold(
          appBar: AppBar(
            leading: Container(),
            iconTheme: const IconThemeData(
              color: Colors.white,
            ),
            shadowColor: theme.weakDividerColor,
            elevation: 1,
            title: Text(
              TIM_t("登录"),
              style: const TextStyle(color: Colors.white, fontSize: 17),
            ),
            flexibleSpace: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    theme.lightPrimaryColor ?? CommonColor.lightPrimaryColor,
                    theme.primaryColor ?? CommonColor.primaryColor
                  ],
                ),
              ),
            ),
          ),
          body: AppLayout(initIMSDK: initIMSDK),
          resizeToAvoidBottomInset: false,
        ));
  }
}

class AppLayout extends StatelessWidget {
  final Function? initIMSDK;
  const AppLayout({Key? key, this.initIMSDK}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        SystemChannels.textInput.invokeMethod('TextInput.hide');
      },
      child: Container(
        color: Colors.white,
        child: Stack(
          children: [
            LoginForm(
              initIMSDK: initIMSDK,
            ),
          ],
        ),
      ),
    );
  }
}

class LoginForm extends StatefulWidget {
  final Function? initIMSDK;
  const LoginForm({Key? key, required this.initIMSDK}) : super(key: key);

  @override
  _LoginFormState createState() => _LoginFormState();
}

class _LoginFormState extends State<LoginForm> {
  final CoreServicesImpl coreInstance = TIMUIKitCore.getInstance();
  int loginType = 0; // 0: 账号密码登录, 1: 手机号验证码登录, 2: 邮箱验证码登录
  bool isPasswordVisible = false; // 控制密码可见性
  bool isAlwaysDevice = true; // 是否常用设备

  String account = '';
  String password = '';
  String answer = '';
  String question = '';

  String phoneVerify = '';
  bool isPhoneVerify = false;
  String phoneVerifyText = '获取验证码';
  int phoneSeconds = 60;
  Timer? _phoneTimer;

  String emailVerify = '';
  bool isEmailVerify = false;
  String emailVerifyText = '获取验证码';
  int emailSeconds = 60;
  Timer? _emailTimer;

  final FocusNode _focusNode = FocusNode();
  final TextEditingController _userIDController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _verificationCodeController =
      TextEditingController();

  @override
  initState() {
    super.initState();
    if (widget.initIMSDK != null) {
      widget.initIMSDK!();
    }
  }

  @override
  void dispose() {
    _focusNode.dispose();
    _userIDController.dispose();
    _passwordController.dispose();
    _phoneController.dispose();
    _emailController.dispose();
    _verificationCodeController.dispose();
    _phoneTimer?.cancel();
    _emailTimer?.cancel();
    super.dispose();
  }

  TextSpan webViewLink(String title, String url) {
    return TextSpan(
      text: TIM_t(title),
      style: const TextStyle(
        color: Color.fromRGBO(0, 110, 253, 1),
      ),
      recognizer: TapGestureRecognizer()
        ..onTap = () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => PrivacyDocument(title: title, url: url),
            ),
          );
        },
    );
  }

  directToHomePage() {
    Routes().directToHomePage();
  }

  /// 获取验证码
  void sendVerificationCode(void Function(void Function() fn) setState) {
    if (loginType == 1) {
      if (account.isEmpty) {
        ToastUtils.toast(TIM_t("请输入手机号"));
        return;
      }
      if (!RegExp(r'^[1][3-9]\d{9}$').hasMatch(account)) {
        ToastUtils.toast(TIM_t("请输入有效的手机号"));
        return;
      }

      if (isPhoneVerify) {
        return;
      }

      _phoneTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
        if (phoneSeconds == 0) {
          _phoneTimer?.cancel();
          phoneSeconds = 60;
          setState(() {
            isPhoneVerify = false;
            phoneVerifyText = '获取验证码';
          });
        } else {
          setState(() {
            phoneSeconds--;
            isPhoneVerify = true;
            phoneVerifyText = '$phoneSeconds s';
          });
        }
      });
    } else if (loginType == 2) {
      if (account.isEmpty) {
        ToastUtils.toast(TIM_t("请输入邮箱"));
        return;
      }

      if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(account)) {
        ToastUtils.toast(TIM_t("请输入有效的邮箱地址"));
        return;
      }

      if (isEmailVerify) {
        return;
      }

      _emailTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
        if (emailSeconds == 0) {
          _emailTimer?.cancel();
          emailSeconds = 60;
          setState(() {
            isEmailVerify = false;
            emailVerifyText = '获取验证码';
          });
        } else {
          setState(() {
            emailSeconds--;
            isEmailVerify = true;
            emailVerifyText = '$emailSeconds s';
          });
        }
      });
    }
  }

  /// 常用设备
  Future<void> setShowVerifyCode() async {
    final deviceId = await AuthService.getDeviceId();
    bool res = true;
    if (account.isNotEmpty && deviceId != null) {
      res = await AuthService.checkDeviceForUser(
        account,
        deviceId,
      );
      isAlwaysDevice = res;
      return;
    }
    isAlwaysDevice = true;
  }

  Future<void> userLogin() async {
    String key = IMDemoConfig.key;
    int sdkAppId = IMDemoConfig.sdkAppID;

    final deviceId = await AuthService.getDeviceId();

    if (key == "" || sdkAppId == 0) {
      ToastUtils.toast(TIM_t("请在 config.dart 中输入 sdkAppID 和 key"));
      return;
    }

    if (account.isEmpty) {
      ToastUtils.toast(TIM_t("请输入登录账号"));
      return;
    }

    if (password.isEmpty) {
      ToastUtils.toast(TIM_t("请输入密码"));
      return;
    }

    if (deviceId == null) {
      ToastUtils.toast(TIM_t("获取设备ID失败"));
      return;
    }

    EasyLoading.show(status: TIM_t("正在登录，请稍后"));

    try {
      await appRequest(
        method: 'post',
        path: 'https://chat.vsl.cn/api/user/login',
        data: {
          'account': account,
          'password': password,
          'loginType': loginType,
          'deviceId': deviceId,
          'answer': answer,
        },
      ).then((res) async {
        debugPrint('login params: ${{
          'account': account,
          'password': password,
          'loginType': loginType,
          'deviceId': deviceId,
          'answer': answer,
        }}');
        debugPrint('login res: ${res.data}');

        if (res.data?['code'] == 1) {
          String userSig = res.data?['data']['userinfo']['im_user_sig'] ?? '';
          String userID = res.data?['data']['userinfo']['username'] ?? '';
          String account = res.data?['data']['userinfo']['account'] ?? '';
          String email = res.data?['data']['userinfo']['email'] ?? '';

          await TUICallKit.instance.login(sdkAppId, userID, userSig);

          var data = await coreInstance.login(
            userID: userID,
            userSig: userSig,
          );

          if (data.code == 0) {
            // 保存登录状态
            await AuthService().saveLoginState(
              isLoggedIn: true,
              userSig: userSig,
              userID: userID,
              account: account,
              email: email,
            );

            if (!(await AuthService.checkDeviceForUser(account, deviceId))) {
              AuthService.addDeviceId(account, deviceId);
            }

            SharedPreferences.getInstance().then((prefs) {
              prefs.setString('userID', userID);
              prefs.setString('userSig', userSig);
            });

            // 登录成功
            initEmoji();
            directToHomePage();
            ToastUtils.toast(TIM_t('登录成功'));
          }
        } else if (res.data?['code'] == 10001) {
          /// 获取安全问题
          question = res.data?['data']['question'] ?? '';
          showSecondPasswordDialog(context);
          return;
        } else {
          ToastUtils.toast(TIM_t(res.data?['msg'] ?? '网络故障，请稍后重试'));
        }
      });
    } catch (e) {
      ToastUtils.toast(TIM_t("网络故障，请稍后重试"));
    } finally {
      setState(() {
        EasyLoading.dismiss();
      });
    }
  }

  void showSecondPasswordDialog(BuildContext context) {
    final TextEditingController passwordController = TextEditingController();

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return Dialog(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16)),
              child: Padding(
                padding:
                    const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const Text(
                      '温馨提示',
                      style:
                          TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 12),
                    Text(
                      loginType == 0
                          ? '你正在使用新设备登录，请验证安全问题'
                          : '你正在使用新设备登录，请输入验证码',
                      textAlign: TextAlign.center,
                      style: const TextStyle(fontSize: 12),
                    ),
                    const SizedBox(height: 20),
                    // G10号框（只读）
                    TextField(
                      controller: TextEditingController(text: account),
                      readOnly: true,
                      decoration: InputDecoration(
                        prefixIcon: loginType == 0
                            ? const Icon(Icons.person)
                            : loginType == 1
                                ? const Icon(Icons.phone)
                                : const Icon(Icons.email),
                        filled: true,
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8)),
                      ),
                    ),
                    const SizedBox(height: 12),

                    // 密码框
                    if (loginType == 0)
                      TextField(
                        controller: passwordController,
                        decoration: InputDecoration(
                          hintText: '请输入答案',
                          prefixIcon: const Icon(Icons.lock),
                          filled: true,
                          fillColor: Colors.grey.shade200,
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(8)),
                        ),
                      ),
                    if (loginType == 1 || loginType == 2)
                      TextField(
                        controller: _verificationCodeController,
                        autofocus: false,
                        decoration: InputDecoration(
                          contentPadding: EdgeInsets.only(
                            left: CommonUtils.adaptWidth(14),
                          ),
                          hintText: TIM_t("请输入验证码"),
                          hintStyle: TextStyle(
                            fontSize: CommonUtils.adaptFontSize(24),
                            color: Colors.grey,
                          ),
                          prefixIcon: const Icon(
                            Icons.lock,
                            color: Colors.grey,
                          ),
                          suffixIcon: TextButton(
                            onPressed: () {
                              sendVerificationCode(setState);
                              answer = passwordController.text;
                            },
                            child: Text(
                              loginType == 1
                                  ? phoneVerifyText
                                  : emailVerifyText,
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: CommonUtils.adaptFontSize(24),
                              ),
                            ),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8.0),
                            borderSide: const BorderSide(color: Colors.grey),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8.0),
                            borderSide: const BorderSide(color: Colors.black),
                          ),
                        ),
                        keyboardType: TextInputType.number,
                        onChanged: (v) {
                          setState(() {
                            if (loginType == 1) {
                              phoneVerify = v;
                            } else {
                              emailVerify = v;
                            }
                          });
                        },
                      ),
                    const SizedBox(height: 6),
                    if (loginType == 0)
                      Align(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          '安全问题：$question',
                          style:
                              const TextStyle(fontSize: 12, color: Colors.red),
                        ),
                      ),
                    const SizedBox(height: 20),

                    // 按钮组
                    Row(
                      children: [
                        Expanded(
                          child: OutlinedButton(
                            onPressed: () {
                              phoneVerifyText = '获取验证码';
                              emailVerifyText = '获取验证码';
                              emailSeconds = 60;
                              phoneSeconds = 60;
                              isPhoneVerify = false;
                              isEmailVerify = false;
                              _phoneTimer?.cancel();
                              _emailTimer?.cancel();
                              Navigator.pop(context);
                            },
                            child: const Text(
                              '取消',
                              style: TextStyle(
                                color: Colors.black,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(width: 10),
                        Expanded(
                          child: ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.black,
                            ),
                            onPressed: () {
                              answer = passwordController.text;
                              userLogin();
                              Navigator.pop(context);
                            },
                            child: const Text(
                              '确认',
                              style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ),
                      ],
                    )
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(
      context,
      designSize: const Size(750, 1624),
      minTextAdapt: true,
    );
    return Stack(
      children: [
        Positioned(
          top: CommonUtils.adaptHeight(80),
          left: 0,
          right: 0,
          child: Center(
            child: SizedBox(
              height: CommonUtils.adaptHeight(200),
              child: Image.asset(
                "assets/logo.png",
                fit: BoxFit.contain,
              ),
            ),
          ),
        ),
        Positioned(
            bottom: CommonUtils.adaptHeight(120),
            child: Container(
              padding: const EdgeInsets.fromLTRB(40, 40, 40, 0),
              height: MediaQuery.of(context).size.height -
                  CommonUtils.adaptHeight(600),
              width: MediaQuery.of(context).size.width,
              child: Form(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    TextField(
                      controller: loginType == 0
                          ? _userIDController
                          : (loginType == 1
                              ? _phoneController
                              : _emailController),
                      autofocus: false,
                      focusNode: _focusNode,
                      decoration: InputDecoration(
                        contentPadding:
                            EdgeInsets.only(left: CommonUtils.adaptWidth(14)),
                        hintText: loginType == 0
                            ? TIM_t("请输入登录账号")
                            : (loginType == 1
                                ? TIM_t("请输入手机号")
                                : TIM_t("请输入邮箱")),
                        hintStyle: TextStyle(
                          fontSize: CommonUtils.adaptFontSize(24),
                          color: Colors.grey,
                        ),
                        prefixIcon: Icon(
                          loginType == 0
                              ? Icons.person
                              : (loginType == 1 ? Icons.phone : Icons.email),
                          color: Colors.grey,
                        ),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8.0),
                          borderSide: const BorderSide(color: Colors.grey),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8.0),
                          borderSide: const BorderSide(color: Colors.black),
                        ),
                      ),
                      keyboardType: loginType == 1
                          ? TextInputType.phone
                          : (loginType == 2
                              ? TextInputType.emailAddress
                              : TextInputType.text),
                      onChanged: (v) {
                        setState(() {
                          account = v;
                        });
                      },
                    ),
                    SizedBox(height: CommonUtils.adaptHeight(34)),
                    TextField(
                      controller: _passwordController,
                      autofocus: false,
                      obscureText: !isPasswordVisible, // 根据状态切换密码可见性
                      decoration: InputDecoration(
                        contentPadding: EdgeInsets.only(
                          left: CommonUtils.adaptWidth(14),
                        ),
                        hintText: TIM_t("请输入密码"),
                        hintStyle: TextStyle(
                          fontSize: CommonUtils.adaptFontSize(24),
                          color: Colors.grey,
                        ),
                        prefixIcon: const Icon(
                          Icons.lock,
                          color: Colors.grey,
                        ),
                        suffixIcon: IconButton(
                          icon: Icon(
                            isPasswordVisible
                                ? Icons.visibility
                                : Icons.visibility_off,
                            color: Colors.grey,
                          ),
                          onPressed: () {
                            setState(() {
                              isPasswordVisible = !isPasswordVisible; // 切换密码可见性
                            });
                          },
                        ),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8.0),
                          borderSide: const BorderSide(color: Colors.grey),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8.0),
                          borderSide: const BorderSide(color: Colors.black),
                        ),
                      ),
                      keyboardType: TextInputType.text,
                      onChanged: (v) {
                        setState(() {
                          password = v;
                        });
                      },
                    ),
                    Container(
                      margin: EdgeInsets.only(top: CommonUtils.adaptHeight(20)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          GestureDetector(
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => const RegisterPage(),
                                ),
                              );
                            },
                            child: Text(
                              TIM_t("没有账号，去注册"),
                              style: TextStyle(
                                color: Colors.blue,
                                fontSize: CommonUtils.adaptFontSize(24),
                              ),
                            ),
                          ),
                          GestureDetector(
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => const ForgetPage(),
                                ),
                              );
                            },
                            child: Text(
                              TIM_t("忘记密码"),
                              style: TextStyle(
                                color: Colors.blue,
                                fontSize: CommonUtils.adaptFontSize(24),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                        top: CommonUtils.adaptHeight(200),
                      ),
                      child: Row(
                        children: [
                          Expanded(
                            child: ElevatedButton(
                                child: Text(
                                  TIM_t("登录"),
                                  style: const TextStyle(color: Colors.white),
                                ),
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: Colors.black,
                                ),
                                onPressed: userLogin),
                          )
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                        top: CommonUtils.adaptHeight(100),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          GestureDetector(
                            onTap: () {
                              if (loginType == 0) return;
                              setState(() {
                                loginType = 0; // 切换到账号密码登录
                                account = '';
                                password = '';
                                _userIDController.clear();
                                _passwordController.clear();
                                _phoneController.clear();
                                _emailController.clear();
                                _verificationCodeController.clear();
                              });
                            },
                            child: Column(
                              children: [
                                Icon(
                                  Icons.person,
                                  color: loginType == 0
                                      ? Colors.black
                                      : Colors.grey,
                                  size: 40,
                                ),
                                Text(
                                  TIM_t("账号登录"),
                                  style: TextStyle(
                                    color: loginType == 0
                                        ? Colors.black
                                        : Colors.grey,
                                    fontSize: CommonUtils.adaptFontSize(24),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(width: CommonUtils.adaptWidth(100)),
                          GestureDetector(
                            onTap: () {
                              if (loginType == 1) return;
                              setState(() {
                                loginType = 1; // 切换到手机号登录
                                account = '';
                                password = '';
                                _userIDController.clear();
                                _passwordController.clear();
                                _phoneController.clear();
                                _emailController.clear();
                                _verificationCodeController.clear();
                              });
                            },
                            child: Column(
                              children: [
                                Icon(
                                  Icons.phone,
                                  color: loginType == 1
                                      ? Colors.black
                                      : Colors.grey,
                                  size: 40,
                                ),
                                Text(
                                  TIM_t("手机号登录"),
                                  style: TextStyle(
                                    color: loginType == 1
                                        ? Colors.black
                                        : Colors.grey,
                                    fontSize: CommonUtils.adaptFontSize(24),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(width: CommonUtils.adaptWidth(100)),
                          GestureDetector(
                            onTap: () {
                              if (loginType == 2) return;
                              setState(() {
                                loginType = 2; // 切换到邮箱登录
                                account = '';
                                password = '';
                                _userIDController.clear();
                                _passwordController.clear();
                                _phoneController.clear();
                                _emailController.clear();
                                _verificationCodeController.clear();
                              });
                            },
                            child: Column(
                              children: [
                                Icon(
                                  Icons.email,
                                  color: loginType == 2
                                      ? Colors.black
                                      : Colors.grey,
                                  size: 40,
                                ),
                                Text(
                                  TIM_t("邮箱登录"),
                                  style: TextStyle(
                                    color: loginType == 2
                                        ? Colors.black
                                        : Colors.grey,
                                    fontSize: CommonUtils.adaptFontSize(24),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            )),
      ],
    );
  }
}
